package org.example.chain;

import org.example.model.FarmMachine;
import org.example.strategy.ObstacleAvoidanceStrategy;
import org.example.strategy.PathPlanningContext;

public class ObstacleAvoidanceHandler extends SafetyHandler {
    private PathPlanningContext pathPlanningContext;

    public ObstacleAvoidanceHandler() {
        pathPlanningContext = new PathPlanningContext();
        pathPlanningContext.setStrategy(new ObstacleAvoidanceStrategy());
    }

    @Override
    public void handleSafetyEvent(FarmMachine machine, String event, SafetyData data) {
        if ("检测到障碍物".equals(event)) {
            System.out.println("障碍物避障处理器处理事件: " + event);
            System.out.println("障碍物信息: " + data.getObstacleInfo());

            pathPlanningContext.planPath(machine);

            boolean avoidanceSuccessful = Math.random() > 0.3;
            data.setObstacleAvoided(avoidanceSuccessful);

            if (avoidanceSuccessful) {
                System.out.println("成功避开障碍物");
                machine.getState().handleEvent(machine, "障碍物已避开");
            } else if (nextHandler != null) {
                System.out.println("无法单独处理，传递给下一个处理器");
                nextHandler.handleSafetyEvent(machine, event, data);
            }
        } else if (nextHandler != null) {
            nextHandler.handleSafetyEvent(machine, event, data);
        }
    }
}